﻿using System;
using System.Collections.Generic;

using System.Text;
using System.IO;

namespace rkShared.BEncode
{
    public class BEncodedString : IBElement
    {
        public BEncodedString()
        {
        }
        /// <summary>
        /// True->Unicode, False->ASCII
        /// </summary>
        /// <param name="value"></param>
        /// <param name="unicode"></param>
        public BEncodedString(string value, bool unicode)
        {
            if (unicode)
                this.Value = Encoding.Unicode.GetBytes(value);
            else
                this.Value = Encoding.ASCII.GetBytes(value);
        }
        /// <summary>
        /// Default ASCII
        /// </summary>
        /// <param name="str"></param>
        public BEncodedString(string str)
        {
            this.Value = Encoding.ASCII.GetBytes(str);
        }
        public BEncodedString(string str, Encoding e)
        {
            if (!string.IsNullOrEmpty(str))
                this.Value = e.GetBytes(str);
        }
        public BEncodedString(byte[] value)
        {
            this.Value = value;
        }
        #region IBElement Members

        public void Encode(BinaryWriter writer)
        {
            if (this.Value != null && this.Value.Length > 0)
            {
                writer.Write(Encoding.ASCII.GetBytes(this.Value.Length.ToString()));
                writer.Write(Encoding.ASCII.GetBytes(":"));
                writer.Write(this.Value);
            }
        }
        public void Decode(byte[] binary)
        {
            this.Value = binary;
        }
        #endregion
        public byte[] Value { get; set; }
        /// <summary>
        /// Converts bytes into a System.String representation as if they were encoded using ASCII encoding. Do not use this property 
        /// if you are not sure about the System.Encoding option you provided while constructin the BEncodedString instance.
        /// </summary>
        public string ValueStr
        {
            get
            {
                return Encoding.ASCII.GetString(this.Value);
            }
            set
            {
                this.Value = Encoding.ASCII.GetBytes(value);
            }
        }
        public string ToString(Encoding e)
        {
            return e.GetString(this.Value);
        }
        public string ToUnicodeString()
        {
            return Encoding.Unicode.GetString(this.Value);
        }
        public override string ToString()
        {
            return this.ToString(Encoding.ASCII);
        }
        #region operators
        public static explicit operator String(BEncodedString value)
        {
            return value.ValueStr;
        }
        public static explicit operator BEncodedString(string value)
        {
            return new BEncodedString(value);
        }
        #endregion
    }
}
